#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 目录定义
install_dir="$HOME/dst"
steamcmd_dir="$HOME/steamcmd"

# 输出函数
function echo_error() { echo -e "${RED}错误: $@${NC}" >&2; }
function echo_success() { echo -e "${GREEN}$@${NC}"; }
function echo_warning() { echo -e "${YELLOW}$@${NC}"; }
function echo_info() { echo -e "${BLUE}$@${NC}"; }
function echo_debug() { echo -e "${CYAN}$@${NC}"; }

function fail() {
    echo_error "$@"
    exit 1
}

function check_for_file() {
    if [ ! -e "$1" ]; then
        return 1
    fi
    return 0
}

function download() {
    local download_url="$1"
    local tries="$2"
    local timeout="$3"

    wget -q --show-progress --tries="$tries" --timeout="$timeout" "$download_url"
    return $?
}

# 设置虚拟内存
function settingSwap() {
    SWAPFILE=/swap.img
    SWAPSIZE=2G

    if [ -f $SWAPFILE ]; then
        echo_success "交换文件已存在，跳过创建步骤"
    else
        echo_info "创建交换文件..."
        sudo fallocate -l $SWAPSIZE $SWAPFILE
        sudo chmod 600 $SWAPFILE
        sudo mkswap $SWAPFILE
        sudo swapon $SWAPFILE
        echo_success "交换文件创建并启用成功"
    fi

    if ! grep -q "$SWAPFILE" /etc/fstab; then
        echo_info "将交换文件添加到 /etc/fstab"
        echo "$SWAPFILE none swap sw 0 0" | sudo tee -a /etc/fstab
        echo_success "交换文件已添加到开机启动"
    else
        echo_success "交换文件已在 /etc/fstab 中，跳过添加步骤"
    fi

    sysctl -w vm.swappiness=20
    sysctl -w vm.min_free_kbytes=100000
    echo -e 'vm.swappiness = 20\nvm.min_free_kbytes = 100000\n' > /etc/sysctl.d/dmp_swap.conf

    echo_success "系统swap设置成功 (System swap setting completed)"
}

# 安装服务器
Install_dst() {
    read -p "您确定要安装 Don't Starve Together 服务器吗？(y/n): " confirm
    if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then
        echo_warning "安装已取消."
        return
    fi

    echo_info "正在安装 Don't Starve Together 服务器..."
    sudo dpkg --add-architecture i386
    sudo apt-get update
    sudo apt-get install -y lib32gcc1
    sudo apt-get install -y libcurl4-gnutls-dev:i386
    sudo apt-get install -y screen
    echo_success "环境依赖安装完毕"

    mkdir -p ~/.klei/DoNotStarveTogether/backups/
    mkdir -p ~/.klei/DoNotStarveTogether/Cluster_1/
    mkdir -p ~/.klei/DoNotStarveTogether/Cluster_1/Master
    mkdir -p ~/.klei/DoNotStarveTogether/Cluster_1/Caves
    touch ~/.klei/DoNotStarveTogether/Cluster_1/cluster_token.txt
    touch ~/.klei/DoNotStarveTogether/Cluster_1/adminlist.txt
    touch ~/.klei/DoNotStarveTogether/Cluster_1/blocklist.txt
    touch ~/.klei/DoNotStarveTogether/Cluster_1/whitelist.txt
    mkdir -p ~/.klei/DoNotStarveTogether/Cluster_2/
    mkdir -p ~/.klei/DoNotStarveTogether/Cluster_2/Master
    mkdir -p ~/.klei/DoNotStarveTogether/Cluster_2/Caves
    touch ~/.klei/DoNotStarveTogether/Cluster_2/cluster_token.txt
    touch ~/.klei/DoNotStarveTogether/Cluster_2/adminlist.txt
    touch ~/.klei/DoNotStarveTogether/Cluster_2/blocklist.txt
    touch ~/.klei/DoNotStarveTogether/Cluster_2/whitelist.txt
    echo_success "饥荒初始文件夹创建完成"

    settingSwap
    echo_info "设置虚拟内存2GB"
    mkdir ~/steamcmd
    cd ~/steamcmd
    
    file_name="steamcmd_linux.tar.gz"
    check_for_file "$file_name"

    if [ $? -eq 0 ]; then
        echo_warning "$file_name 存在，正在删除..."
        rm "$file_name"
    else
        echo_info "$file_name 不存在，继续下载steamcmd"
    fi

    wget https://steamcdn-a.akamaihd.net/client/installer/steamcmd_linux.tar.gz
    tar -xvzf steamcmd_linux.tar.gz
    ./steamcmd.sh +login anonymous +force_install_dir "$install_dir" +app_update 343050 validate +quit

    cp ~/steamcmd/linux32/libstdc++.so.6 ~/dst/bin/lib32/
    cp ~/steamcmd/linux32/steamclient.so ~/dst/bin/lib32/
    echo_success "MOD更新bug已修复"
    echo_success "Don't Starve Together 服务器安装完成."
}

# 更新服务器
Update_dst() {
    echo_info "正在更新 Don't Starve Together 服务器..."
    cd "$steamcmd_dir" || fail
    ./steamcmd.sh +login anonymous +force_install_dir "$install_dir" +app_update 343050 validate +quit
    echo_success "服务器更新完成,请重新执行脚本"
    cp ~/steamcmd/linux32/steamclient.so ~/dst/bin/lib32/
    echo_success "MOD更新bug已修复"
}

# 更新指定 Cluster 的模组
function AddAutoUpdateMod() {
    local cluster_choice="$1"
    local modTotal
    local modID

    local cluster_file
    if [[ "$cluster_choice" -eq 1 ]]; then
        cluster_file="$HOME/.klei/DoNotStarveTogether/Cluster_1/Master/modoverrides.lua"
    elif [[ "$cluster_choice" -eq 2 ]]; then
        cluster_file="$HOME/.klei/DoNotStarveTogether/Cluster_2/Master/modoverrides.lua"
    else
        echo_error "无效的选择."
        return
    fi

    local mods_file="$HOME/dst/mods/dedicated_server_mods_setup.lua"
    check_for_file "$cluster_file"

    modTotal=$(grep -c 'workshop-' "$cluster_file")

    if [[ $modTotal -eq 0 ]]; then
        echo_warning "没有发现模组文件！"
        return
    fi

    for item in $(seq "$modTotal"); do
        modID=$(grep 'workshop-' "$cluster_file" | cut -d '"' -f2 | sed 's#workshop-##g' | awk "NR==$item{print \$0}")

        if [[ $(grep -c "$modID" "$mods_file") -eq 0 ]]; then
            echo "        ServerModSetup(\"$modID\")" >> "$mods_file"
            echo ""
            echo_success "$modID 模组添加完成！"
        else
            echo ""
            echo_warning "这个 $modID 模组之前已被添加！"
        fi
    done
    
    sleep 3s
}

# 更新指定 Cluster 的模组
function UpdateMods() {
    local cluster_choice
    echo "============================================"
    echo_info "请选择要更新的MOD配置:"
    echo "1. 更新 Cluster_1 模组配置文件"
    echo "2. 更新 Cluster_2 模组配置文件"
    echo "0. 返回主菜单"

    while true; do
        read -p "输入您的选择 (0-2): " cluster_choice
        if [[ "$cluster_choice" =~ ^[0-2]$ ]]; then
            break
        else
            echo_error "无效选择. 请重试."
        fi
    done

    case $cluster_choice in
        1)
            echo_info "正在更新 Cluster_1 模组配置文件..."
            AddAutoUpdateMod 1
            echo_success "Cluster_1 模组配置文件更新完成."
            ;;
        2)
            echo_info "正在更新 Cluster_2 模组配置文件..."
            AddAutoUpdateMod 2
            echo_success "Cluster_2 模组配置文件更新完成."
            ;;
        0)
            break
            ;;
    esac
}

# 启动服务器
function start_server() {
    local cluster=$1
    local shard=$2
    local screen_name="$cluster$shard"
    local token_file="$HOME/.klei/DoNotStarveTogether/$cluster/cluster_token.txt"
    local cluster_dir="$HOME/.klei/DoNotStarveTogether/$cluster"

    # 创建集群目录（如果不存在）
    if [ ! -d "$cluster_dir" ]; then
        echo_info "📁 集群目录不存在，正在创建: $cluster_dir"
        mkdir -p "$cluster_dir" || {
            echo_error "✘ 无法创建集群目录: $cluster_dir"
            return 1
        }
        echo_success "✔ 集群目录创建成功！"
    fi

    # 检查令牌文件
    if [[ ! -f "$token_file" ]] || [[ ! -s "$token_file" ]]; then
        echo_warning "⚠️ 令牌文件不存在或为空: $token_file"
        echo_info "📋 请粘贴您的服务器令牌（一行内容），完成后按 Ctrl+D 保存:"
        
        # 创建令牌文件
        cat > "$token_file" || {
            echo_error "✘ 无法创建令牌文件: $token_file"
            return 1
        }
        
        # 再次检查令牌文件
        if [[ ! -s "$token_file" ]]; then
            echo_error "✘ 令牌文件仍然为空，无法启动服务器"
            return 1
        fi
        
        echo_success "✔ 令牌文件已创建并保存！"
    fi

    # 检查服务器是否已在运行
    if screen -list | grep -q "$screen_name"; then
        echo
        echo_warning "======================================"
        echo_warning "⚠️ $screen_name 服务器已经在运行."
        echo_warning "======================================"
        echo
        return 0
    fi

    # 启动服务器
    cd ~/dst/bin/ || {
        echo
        echo_error "======================================"
        echo_error "✘ 无法进入服务器目录: ~/dst/bin/"
        echo_error "✘ 请检查是否已正确安装饥荒服务器程序"
        echo_error "======================================"
        echo
        return 1
    }
    
    echo_info "🚀 正在启动 $screen_name 服务器..."
    screen -dmS "$screen_name" ./dontstarve_dedicated_server_nullrenderer -console -cluster "$cluster" -shard "$shard"
    
    # 添加延迟确保进程创建
    sleep 1
    
    # 醒目显示启动结果
    if screen -list | grep -q "$screen_name"; then
        echo
        echo_success "=================================================="
        echo_success "✔✔✔ $screen_name 服务器已成功启动! ✔✔✔"
        echo_success "=================================================="
        echo_success "📺 返回主菜单选项3可以查看已启动的服务器"
        echo_success "📺 返回主菜单选项3可以查看已启动的服务器"
        echo_success "🛑 如果未找到程序，请查看服务器日志"
        echo_success "=================================================="
        echo
    else
        echo
        echo_error "=================================================="
        echo_error "✘✘✘ $screen_name 服务器启动失败! ✘✘✘"
        echo_error "=================================================="
        echo_error "❗ 请检查以下可能原因:"
        echo_error "  1. 饥荒程序是否正确安装"
        echo_error "  2. 存档配置目录是否存在"
        echo_error "  3. 系统资源是否充足"
        echo_error "=================================================="
        echo
        return 1
    fi
}

# 备份存档
BackupSaves() {
    local backup_choice
    local backup_dirs="$HOME/.klei/DoNotStarveTogether/backups"
    local timestamp=$(date +"%Y-%m-%d_%H-%M-%S")
    
    # 检查备份目录是否存在，不存在则创建
    if [ ! -d "$backup_dirs" ]; then
        echo_info "备份目录不存在，正在创建: $backup_dirs"
        mkdir -p "$backup_dirs" || {
            echo_error "无法创建备份目录: $backup_dirs"
            return 1
        }
        echo_success "备份目录创建成功！"
    fi

    while true; do
        echo "============================================"
        echo_info "备份前建议关闭世界！"
        echo_info "请选择要备份的存档:"
        echo "1. 备份 Cluster_1 存档"
        echo "2. 备份 Cluster_2 存档"
        echo "0. 返回主菜单"

        read -p "输入您的选择 (0-2): " backup_choice

        case $backup_choice in
            1)
                echo_info "正在备份 Cluster_1 存档..."
                cd "$HOME/.klei/DoNotStarveTogether/Cluster_1" || { 
                    echo_error "无法进入目录: $HOME/.klei/DoNotStarveTogether/Cluster_1"
                    continue
                }
                local backup_file="$backup_dirs/Cluster_1_backup_$timestamp.tar.gz"
                tar -czf "$backup_file" . || {
                    echo_error "备份过程中出错"
                    continue
                }
                echo_success "备份完成，文件位置: $backup_file"
                ;;
            2)
                echo_info "正在备份 Cluster_2 存档..."
                cd "$HOME/.klei/DoNotStarveTogether/Cluster_2" || { 
                    echo_error "无法进入目录: $HOME/.klei/DoNotStarveTogether/Cluster_2"
                    continue
                }
                local backup_file="$backup_dirs/Cluster_2_backup_$timestamp.tar.gz"
                tar -czf "$backup_file" . || {
                    echo_error "备份过程中出错"
                    continue
                }
                echo_success "备份完成，文件位置: $backup_file"
                ;;
            0)
                break
                ;;
            *)
                echo_error "无效选择. 请重试."
                ;;
        esac
    done
}

RestoreSaves() {
    # 自动查找备份文件
    local backup_files=()
    local backup_dirs="$HOME/.klei/DoNotStarveTogether/backups"
    
    echo_info "正在扫描备份文件..."
    for dir in "${backup_dirs[@]}"; do
        if [ -d "$dir" ]; then
            while IFS= read -r -d $'\0' file; do
                backup_files+=("$file")
            done < <(find "$dir" -maxdepth 3 -type f \( -name "*.tar.gz" -o -name "*.zip" \) -print0 2>/dev/null)
        fi
    done
    
    # 如果没有找到备份文件
    if [ ${#backup_files[@]} -eq 0 ]; then
        echo_error "未找到任何备份文件。请确保备份文件位于以下位置:"
        echo "  - $HOME/.klei/DoNotStarveTogether/backups"
        read -p "按回车键返回主菜单..."
        return
    fi
    
    # 检查并自动安装 unzip（用于解压 .zip 文件）
    local unzip_installed=true
    if ! command -v unzip &> /dev/null; then
        unzip_installed=false
        echo_warning "未找到 unzip 工具，正在尝试自动安装..."
        
        # 根据不同的包管理器尝试安装
        if command -v apt-get &> /dev/null; then
            sudo apt-get update && sudo apt-get install -y unzip
        elif command -v yum &> /dev/null; then
            sudo yum install -y unzip
        else
            echo_error "无法自动安装 unzip，请手动安装后再试"
            echo "在 Debian/Ubuntu 系统上使用: sudo apt install unzip"
            echo "在 RedHat/CentOS 系统上使用: sudo yum install unzip"
            read -p "按回车键继续..."
        fi
        
        # 再次检查是否安装成功
        if command -v unzip &> /dev/null; then
            unzip_installed=true
            echo_success "unzip 安装成功！"
        else
            echo_error "unzip 安装失败，请手动安装"
        fi
    fi
    
    while true; do
        echo "============================================"
        echo_info "请选择要恢复的存档文件:"
        echo "0. 返回主菜单"
        
        # 显示备份文件列表
        local i=1
        for file in "${backup_files[@]}"; do
            local filename=$(basename "$file")
            local filesize=$(du -h "$file" | cut -f1)
            local filedate=$(date -r "$file" "+%Y-%m-%d %H:%M")
            
            # 标记无法处理的 .zip 文件
            if [[ "$filename" == *.zip ]] && ! $unzip_installed; then
                printf "%2d) %-45s %6s %s [需要 unzip]\n" "$i" "$filename" "$filesize" "$filedate"
            else
                printf "%2d) %-45s %6s %s\n" "$i" "$filename" "$filesize" "$filedate"
            fi
            ((i++))
        done
        
        # 让用户选择文件
        read -p "输入文件编号 (0-${#backup_files[@]}): " file_choice
        
        # 检查输入是否有效
        if [[ "$file_choice" == "0" ]]; then
            return
        elif [[ "$file_choice" =~ ^[0-9]+$ ]] && [ "$file_choice" -ge 1 ] && [ "$file_choice" -le ${#backup_files[@]} ]; then
            local backup_path="${backup_files[$((file_choice-1))]}"
            
            # 检查 .zip 文件是否需要 unzip
            if [[ "$backup_path" == *.zip ]] && ! $unzip_installed; then
                echo_error "无法解压 .zip 文件，因为 unzip 未安装"
                read -p "按回车键继续..."
                continue
            fi
            
            # 自动检测存档类型
            local cluster_type=""
            if [[ "$backup_path" == *"Cluster_1"* ]]; then
                cluster_type="Cluster_1"
            elif [[ "$backup_path" == *"Cluster_2"* ]]; then
                cluster_type="Cluster_2"
            else
                # 无法自动识别，让用户选择
                echo "无法识别存档类型，请手动选择恢复到:"
                echo "1. Cluster_1"
                echo "2. Cluster_2"
                read -p "输入您的选择 (1-2): " cluster_choice
                
                case $cluster_choice in
                    1) cluster_type="Cluster_1" ;;
                    2) cluster_type="Cluster_2" ;;
                    *) 
                        echo_error "无效选择"
                        continue
                        ;;
                esac
            fi
            
            local target_dir="$HOME/.klei/DoNotStarveTogether/$cluster_type"
            
            # 确认操作
            echo_warning "警告：这将覆盖 $target_dir 中的现有存档！"
            read -p "确认恢复存档？(y/n): " confirm
            if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
                echo_info "恢复操作已取消"
                continue
            fi

            #删除旧存档
            rm -rf "$target_dir/Master/save"/*
            rm -rf "$target_dir/Caves/save"/*

            # 添加延迟确保存档已删除
            sleep 3
            
            # 创建目标目录（如果不存在）
            mkdir -p "$target_dir"
            
            # 执行恢复操作
            echo_info "正在恢复 $cluster_type 存档..."
            
            if [[ "$backup_path" == *.tar.gz ]]; then
                tar -xzf "$backup_path" -C "$target_dir"
            elif [[ "$backup_path" == *.zip ]]; then
                unzip -o "$backup_path" -d "$target_dir"
            fi
            
            # 检查恢复是否成功
            if [ $? -eq 0 ]; then
                echo
                echo_success "=================================================="
                echo_success "✔✔✔ 存档恢复成功！ ✔✔✔"
                echo_success "=================================================="
                echo_success "🛑 恢复位置: $target_dir"
                echo_success "📺 启动服务器前请务必在选项5更新mod配置！"
                echo_success "📺 启动服务器前请务必在选项5更新mod配置！"
                echo_success "=================================================="
                echo
                read -p "按回车键继续..."
            else
                echo
                echo_success "=================================================="
                echo_success "✘✘✘ 恢复过程中出错！ ✘✘✘"
                echo_success "=================================================="
                echo
                read -p "按回车键继续..."
            fi
        else
            echo_error "无效选择，请输入 0-${#backup_files[@]} 之间的数字"
        fi
    done
}

# 删除存档
function DeleteSaves() {
    local cluster_choice
    while true; do
        echo "============================================"
        echo_info "请选择要删除的存档:"
        echo "1. 删除 Cluster_1 存档"
        echo "2. 删除 Cluster_2 存档"
        echo "0. 返回上一级菜单"

        read -p "输入您的选择 (0-2): " cluster_choice
        if [[ "$cluster_choice" =~ ^[0-2]$ ]]; then
            if [[ "$cluster_choice" -eq 0 ]]; then
                return
            fi

            case $cluster_choice in
                1)
                    echo_info "正在删除 Cluster_1 存档..."
                    rm -rf "$HOME/.klei/DoNotStarveTogether/Cluster_1/Master/save"/*
                    rm -rf "$HOME/.klei/DoNotStarveTogether/Cluster_1/Caves/save"/*
                    echo_success "Cluster_1 存档已删除."
                    ;;
                2)
                    echo_info "正在删除 Cluster_2 存档..."
                    rm -rf "$HOME/.klei/DoNotStarveTogether/Cluster_2/Master/save"/*
                    rm -rf "$HOME/.klei/DoNotStarveTogether/Cluster_2/Caves/save"/*
                    echo_success "Cluster_2 存档已删除."
                    ;;
                0)
                    break
                    ;;
            esac
        else
            echo_error "无效选择. 请重试."
        fi
    done
}

# 定期检查
function run_monitoring() {
    local session_name=$1
    local master_func=$2
    local caves_func=$3

    screen -dmS "$session_name" bash -c "
        source ./ms.sh
        while true; do
            ${master_func}
            ${caves_func}
            sleep 180
        done
    "
}

# 设置服务器维护任务函数
function setup_maintenance_task() {
    local hour=""
    
    # 获取当前小时作为默认值
    local default_hour=$(date +%H)
    
    echo_info "🕒 设置服务器维护任务"
    echo_info "维护任务包括："
    echo "  - 维护前5分钟发送公告"
    echo "  - 维护前2分钟自动保存"
    echo "  - 指定整点时间关闭所有服务器"
    echo ""
    
    # 输入小时
    while true; do
        read -p "请输入维护时间的小时 (0-23) [默认: $default_hour]: " hour
        if [[ -z "$hour" ]]; then
            hour="$default_hour"
        fi
        
        if [[ "$hour" =~ ^[0-9]+$ ]] && [ "$hour" -ge 0 ] && [ "$hour" -le 23 ]; then
            break
        else
            echo_error "请输入0-23之间的有效数字"
        fi
    done
    
    # 固定分钟为0（整点）
    local minute="00"
    
    # 格式化时间显示
    local formatted_time=$(printf "%02d:%02d" "$hour" "$minute")
    
    # 计算提前时间（分钟固定为55和58）
    local announce_minute="55"
    local save_minute="58"
    local announce_hour=$((hour - 1))
    local save_hour=$((hour - 1))
    
    # 处理小时负数的情况（当hour=0时）
    if [ $announce_hour -lt 0 ]; then
        announce_hour=23
    fi
    
    if [ $save_hour -lt 0 ]; then
        save_hour=23
    fi
    
    # 显示设置信息
    echo ""
    echo_success "📋 维护任务计划如下："
    echo_success "  ⏰ 维护时间: $formatted_time (整点)"
    echo_success "  📢 公告时间: $(printf "%02d:%02d" "$announce_hour" "$announce_minute") (提前5分钟)"
    echo_success "  💾 保存时间: $(printf "%02d:%02d" "$save_hour" "$save_minute") (提前2分钟)"
    echo ""
    
    # 确认设置
    read -p "确认设置以上维护任务？(y/n): " confirm
    if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then
        echo_warning "已取消设置维护任务"
        return
    fi
    
    # 删除现有维护任务
    remove_maintenance_task silent
    
    # 添加新的cron任务
    local temp_cron=$(mktemp)
    crontab -l 2>/dev/null > "$temp_cron"
    
    # 添加公告任务
    echo "$announce_minute $announce_hour * * * if screen -list | grep -q 'Cluster_1Master'; then screen -S Cluster_1Master -p 0 -X stuff 'c_announce(\"服务器将于5分钟后维护重启\")\\n'; fi; if screen -list | grep -q 'Cluster_2Master'; then screen -S Cluster_2Master -p 0 -X stuff 'c_announce(\"服务器将于5分钟后维护重启\")\\n'; fi" >> "$temp_cron"
    
    # 添加保存任务
    echo "$save_minute $save_hour * * * if screen -list | grep -q 'Cluster_1Master'; then screen -S Cluster_1Master -p 0 -X stuff 'c_save()\\n'; fi; if screen -list | grep -q 'Cluster_2Master'; then screen -S Cluster_2Master -p 0 -X stuff 'c_save()\\n'; fi" >> "$temp_cron"
    
    # 添加关闭服务器任务
    echo "$minute $hour * * * screen -X -S Cluster_1Master quit && screen -X -S Cluster_1Caves quit && screen -X -S Cluster_2Master quit && screen -X -S Cluster_2Caves quit" >> "$temp_cron"
    
    # 安装新的cron任务
    crontab "$temp_cron"
    rm -f "$temp_cron"
    
    echo ""
    echo_success "=================================================="
    echo_success "✅ 服务器维护任务已成功设置！"
    echo_success "=================================================="
    echo_success "🕒 维护时间: 每天 $formatted_time (整点)"
    echo_success "📢 提前公告: 每天 $(printf "%02d:%02d" "$announce_hour" "$announce_minute")"
    echo_success "💾 自动保存: 每天 $(printf "%02d:%02d" "$save_hour" "$save_minute")"
    echo_success "🛑 服务器关闭: 每天 $formatted_time"
    echo_success "=================================================="
    echo ""
    
    # 显示当前cron任务
    show_maintenance_status
}

# 删除服务器维护任务函数
function remove_maintenance_task() {
    local silent="${1:-}"
    
    if [[ "$silent" != "silent" ]]; then
        echo_info "正在删除服务器维护任务..."
    fi
    
    # 创建临时cron文件，过滤掉维护任务
    local temp_cron=$(mktemp)
    crontab -l 2>/dev/null | grep -v -E '(Cluster_1Master|Cluster_2Master|服务器维护)' > "$temp_cron" || true
    
    # 如果文件为空，删除crontab
    if [[ ! -s "$temp_cron" ]]; then
        crontab -r 2>/dev/null || true
    else
        crontab "$temp_cron"
    fi
    
    rm -f "$temp_cron"
    
    if [[ "$silent" != "silent" ]]; then
        echo_success "✅ 所有服务器维护任务已删除"
        show_maintenance_status
    fi
}

# 显示维护任务状态函数
function show_maintenance_status() {
    echo_info "📋 当前维护任务状态:"
    
    local has_tasks=0
    local cron_list=$(crontab -l 2>/dev/null || echo "")
    
    if [[ -z "$cron_list" ]]; then
        echo_warning "  暂无维护任务"
        return
    fi
    
    # 查找维护相关任务
    while IFS= read -r line; do
        if [[ "$line" =~ (Cluster_1Master|Cluster_2Master) ]]; then
            has_tasks=1
            if [[ "$line" =~ c_announce ]]; then
                echo_success "  📢 公告任务: $(echo "$line" | cut -d' ' -f1,2)* * *"
            elif [[ "$line" =~ c_save ]]; then
                echo_success "  💾 保存任务: $(echo "$line" | cut -d' ' -f1,2)* * *"
            elif [[ "$line" =~ screen.*quit ]]; then
                echo_success "  🛑 关闭任务: $(echo "$line" | cut -d' ' -f1,2)* * *"
            fi
        fi
    done <<< "$cron_list"
    
    if [[ $has_tasks -eq 0 ]]; then
        echo_warning "  暂无维护任务"
    fi
}

# 监控崩溃重启
function ms_servers() {
    # 检查并确保 ms.sh 存在
    check_for_file "ms.sh"
    if [ $? -ne 0 ]; then
        echo_info "正在下载监测脚本"
        if download "https://gitee.com/xiaochency/dst/raw/master/ms.sh" 5 10; then
            chmod 755 ms.sh
            echo_success "已下载监测脚本，继续执行监控功能"
        else
            echo_error "下载 ms.sh 失败！请检查网络连接或 URL。"
            return 1
        fi
    fi

    while true; do
        echo "============================================"
        echo_success "请选择要执行的操作:"
        echo "1. 监控Cluster_1崩溃重启"
        echo "2. 监控Cluster_2崩溃重启"
        echo "3. 关闭监控脚本"
        echo "4. 设置服务器维护任务"
        echo "5. 删除服务器维护任务"
        echo "6. 查看当前维护任务状态"
        echo "0. 返回主菜单"

        read -p "请输入选项 (0-6): " choice

        case $choice in
            1)
                run_monitoring "111" "monitor_master1" "monitor_caves1"
                echo_success "已在后台启动 Cluster_1 监控脚本 (会话名: 111)"
                ;;
            2)
                run_monitoring "222" "monitor_master2" "monitor_caves2"
                echo_success "已在后台启动 Cluster_2 监控脚本 (会话名: 222)"
                ;;
            3)
                screen -list | grep -E '111|222' | cut -d. -f1 | awk '{print $1}' | xargs kill
                echo_success "已关闭监控脚本..."
                ;;
            4)
                setup_maintenance_task
                ;;
            5)
                remove_maintenance_task
                ;;
            6)
                show_maintenance_status
                ;;
            0)
                echo_info "返回主菜单..."
                return
                ;;
            *)
                echo_error "无效的选项,请重试。"
                ;;
        esac
    done
}

# 发送公告函数
send_announcement() {
    local cluster_name="$1"
    read -p "请输入要发送的公告内容: " announcement

    local master_server="${cluster_name}Master"

    if [[ "$master_server" == "Cluster_1Master" || "$master_server" == "Cluster_2Master" ]]; then
        screen -S "$master_server" -X stuff "c_announce(\"$announcement\")\n"
        echo_success "公告已发送到 $cluster_name 的 Master 服务器。"
    else
        echo_error "无效的集群名称。"
    fi
}

# 回档服务器函数
rollback_server() {
    local cluster_name="$1"
    local rollback_count="$2"

    local master_server="${cluster_name}Master"

    if [[ "$master_server" == "Cluster_1Master" || "$master_server" == "Cluster_2Master" ]]; then
        echo_info "正在回档 $cluster_name 的 Master 服务器 $rollback_count 次..."
        screen -S "$master_server" -X stuff "c_rollback($rollback_count)\n"
        echo_success "$cluster_name 的 Master 服务器已尝试回档。"
    else
        echo_error "无效的集群名称。"
    fi
}

# 重置世界函数
regenerate_world() {
    local cluster_name="$1"
    
    local master_server="${cluster_name}Master"

    read -p "您确定要重置这个世界吗？(y/n): " confirm
    if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then
        echo_warning "已取消."
        return
    fi
    
    if [[ "$master_server" == "Cluster_1Master" || "$master_server" == "Cluster_2Master" ]]; then
        echo_info "正在重置 $cluster_name 的世界..."
        screen -S "$master_server" -X stuff "c_regenerateworld()\n"
        echo_success "$cluster_name 的世界重置指令已发送。"
    else
        echo_error "无效的集群名称。"
    fi
}

# 拉黑玩家函数
ban_player() {
    local cluster_name="$1"
    read -p "请输入要拉黑的玩家 ID (userid): " userid

    if [[ -z "$userid" ]]; then
        echo_error "玩家 ID 不能为空。"
        return 1
    fi

    local master_server="${cluster_name}Master"

    if [[ "$master_server" == "Cluster_1Master" || "$master_server" == "Cluster_2Master" ]]; then
        echo_info "正在拉黑 $cluster_name 的 Master 服务器上的玩家 $userid..."
        screen -S "$master_server" -X stuff "TheNet:Ban(\"$userid\")\n"
        echo_success "已尝试在 $cluster_name 的 Master 服务器上拉黑玩家 $userid。"
    else
        echo_error "无效的集群名称。"
    fi
}

# 服务器控制台函数
server_console() {
    while true; do
        echo "============================================"
        echo_info "服务器控制台"
        echo "请选择一个选项:"
        echo "1. 发送服务器公告"
        echo "2. 服务器回档"
        echo "3. 拉黑玩家"
        echo "4. 服务器重置世界"
        echo "0. 返回主菜单"

        read -p "输入您的选择 (0-4): " console_choice
        case $console_choice in
            1)
                while true; do
                    echo_info "请选择要发公告的服务器:"
                    echo "1. Cluster_1"
                    echo "2. Cluster_2"
                    echo "0. 返回服务器控制台"
                    read -p "输入您的选择 (0-2): " announce_choice
                    case $announce_choice in
                        1) send_announcement "Cluster_1" ;;
                        2) send_announcement "Cluster_2" ;;
                        0) break ;;
                        *) echo_error "无效选择. 请重试." ;;
                    esac
                done
                ;;
            2)
                while true; do
                    echo_info "请选择要回档的服务器:"
                    echo "1. Cluster_1"
                    echo "2. Cluster_2"
                    echo "0. 返回服务器控制台"
                    read -p "输入您的选择 (0-2): " rollback_choice
                    case $rollback_choice in
                        1)
                            read -p "请输入回档次数: " rollback_count
                            rollback_server "Cluster_1" "$rollback_count"
                            ;;
                        2)
                            read -p "请输入回档次数: " rollback_count
                            rollback_server "Cluster_2" "$rollback_count"
                            ;;
                        0) break ;;
                        *) echo_error "无效选择. 请重试." ;;
                    esac
                done
                ;;
            3)
                while true; do
                    echo_info "请选择要拉黑玩家的服务器:"
                    echo "1. Cluster_1"
                    echo "2. Cluster_2"
                    echo "0. 返回服务器控制台"
                    read -p "输入您的选择 (0-2): " ban_choice
                    case $ban_choice in
                        1) ban_player "Cluster_1" ;;
                        2) ban_player "Cluster_2" ;;
                        0) break ;;
                        *) echo_error "无效选择. 请重试." ;;
                    esac
                done
                ;;
            4)
                while true; do
                    echo_info "请选择要重置世界的服务器:"
                    echo "1. Cluster_1"
                    echo "2. Cluster_2"
                    echo "0. 返回服务器控制台"
                    read -p "输入您的选择 (0-2): " regenerate_world
                    case $regenerate_world in
                        1)
                            regenerate_world "Cluster_1" "$regenerate_world"
                            ;;
                        2)
                            regenerate_world "Cluster_2" "$regenerate_world"
                            ;;
                        0) break ;;
                        *) echo_error "无效选择. 请重试." ;;
                    esac
                done
                ;; 
            0) break ;;
            *) echo_error "无效选择. 请重试." ;;
        esac
    done
}

# 保存服务器函数
shutdown_server() {
    while true; do
        echo "============================================"
        echo_info "请选择一个选项:"
        echo "1. 关闭Cluster_1服务器"
        echo "2. 关闭Cluster_2服务器"
        echo "0. 返回主菜单"
        echo_warning "在关闭服务器前会自动保存！"

        read -p "输入您的选择 (0-2): " view_choice
        case $view_choice in
            1)
                echo_info "正在保存Cluster_1服务器.."
                screen -X -S Cluster_1Master stuff "c_save()\n"
                sleep 6
                echo_info "正在关闭Cluster_1服务器.."
                screen -X -S Cluster_1Master quit
                screen -X -S Cluster_1Caves quit
                echo_success "Cluster_1服务器已关闭."
                ;;
            2)
                echo_info "正在保存Cluster_2服务器.."
                screen -X -S Cluster_2Master stuff "c_save()\n"
                sleep 6
                echo_info "正在关闭Cluster_2服务器.."
                screen -X -S Cluster_2Master quit
                screen -X -S Cluster_2Caves quit
                echo_success "Cluster_2服务器已关闭."
                ;;
            0)
                break
                ;;
            *)
                echo_error "无效选择. 请重试."
                ;;
        esac
    done
}

# 服务器状态
show_server_status() {
    echo "=== 当前服务器状态 ==="
    local clusters=("Cluster_1" "Cluster_2")
    local shards=("Master" "Caves")
    
    # 记录集群运行状态
    local cluster1_running=0
    local cluster2_running=0
    
    for cluster in "${clusters[@]}"; do
        for shard in "${shards[@]}"; do
            local screen_name="${cluster}${shard}"
            if screen -list | grep -q "$screen_name"; then
                echo "✅ ${cluster}.${shard} - 运行中"
                # 设置集群运行状态
                if [[ "$cluster" == "Cluster_1" ]]; then
                    cluster1_running=1
                else
                    cluster2_running=1
                fi
            else
                echo "❌ ${cluster}.${shard} - 未运行"
            fi
        done
    done
    echo "===================="
    
    # 如果没有集群运行，直接返回
    if [[ $cluster1_running -eq 0 && $cluster2_running -eq 0 ]]; then
        echo_warning "没有检测到运行中的服务器，跳过直连信息显示"
        return
    fi
    
    echo
    echo "=== 存档直连信息 ==="
    
    # 第一步：获取本机公网IP
    local A1
    echo_info "正在获取本机公网IP..."
    A1=$(curl -s --connect-timeout 5 https://api.ipify.org 2>/dev/null || curl -s --connect-timeout 5 https://ipinfo.io/ip 2>/dev/null || echo "未知")
    A1=$(echo "$A1" | tr -d '\n\r')  # 添加这行清理换行符
    
    if [[ "$A1" == "未知" ]]; then
        echo_warning "无法获取公网IP，请检查网络连接"
    else
        echo_success "本机公网IP: $A1"
    fi
    
    # 检查Cluster_1的配置
    local server_ini_file="$HOME/.klei/DoNotStarveTogether/Cluster_1/Master/server.ini"
    local A2="10999"  # 默认端口
    local cluster1_available=0
    
    if [[ -f "$server_ini_file" ]]; then
        local port_line=$(grep -E '^server_port\s*=' "$server_ini_file" | head -1)
        if [[ -n "$port_line" ]]; then
            A2=$(echo "$port_line" | sed 's/.*=\s*//' | tr -d ' ')
            cluster1_available=1
        else
            echo_warning "Cluster_1未找到server_port配置,使用默认端口10999"
        fi
    else
        echo_warning "Cluster_1的server.ini文件不存在,使用默认端口10999"
    fi
    
    # 检查Cluster_2的配置
    local server_ini_file2="$HOME/.klei/DoNotStarveTogether/Cluster_2/Master/server.ini"
    local B2="10999"  # 默认端口
    local cluster2_available=0
    
    if [[ -f "$server_ini_file2" ]]; then
        local port_line2=$(grep -E '^server_port\s*=' "$server_ini_file2" | head -1)
        if [[ -n "$port_line2" ]]; then
            B2=$(echo "$port_line2" | sed 's/.*=\s*//' | tr -d ' ')
            cluster2_available=1
        else
            echo_warning "Cluster_2未找到server_port配置,使用默认端口10999"
        fi
    else
        echo_warning "Cluster_2的server.ini文件不存在,使用默认端口10999"
    fi

    # 打印直连命令
    if [[ "$A1" != "未知" ]]; then
    echo
    echo_success "════════════════════════════════════════════"
    
    # 清理IP地址和端口号
    local clean_A1=$(echo "$A1" | tr -d '\n\r' | sed 's/[^0-9.]//g')
    local clean_A2=$(echo "$A2" | tr -d '\n\r' | sed 's/[^0-9]//g')
    local clean_B2=$(echo "$B2" | tr -d '\n\r' | sed 's/[^0-9]//g')
    
    # 构建直连命令
    local connect_cmd1=$(printf 'c_connect("%s", %s)' "$clean_A1" "$clean_A2")
    local connect_cmd2=$(printf 'c_connect("%s", %s)' "$clean_A1" "$clean_B2")
    
    # Cluster_1 显示
    if [[ $cluster1_available -eq 1 ]]; then
        if [[ $cluster1_running -eq 1 ]]; then
            echo_success "📡 Cluster_1 [🟢 运行中]"
        else
            echo_warning "📡 Cluster_1 [🔴 未运行]"
        fi
        echo "$connect_cmd1"
        echo  # 空行分隔
    fi
    
    # Cluster_2 显示
    if [[ $cluster2_available -eq 1 ]]; then
        if [[ $cluster2_running -eq 1 ]]; then
            echo_success "📡 Cluster_2 [🟢 运行中]"
        else
            echo_warning "📡 Cluster_2 [🔴 未运行]"
        fi
        echo "$connect_cmd2"
        echo  # 空行分隔
    fi
    
    # 如果没有可用的集群配置
    if [[ $cluster1_available -eq 0 && $cluster2_available -eq 0 ]]; then
        echo_warning "未找到有效的服务器配置"
    elif [[ $cluster1_running -eq 0 && $cluster2_running -eq 0 ]]; then
        echo_warning "当前没有运行中的服务器，以上为预设直连命令"
    fi
    
    echo_success "════════════════════════════════════════════"
    echo_info "💡 在游戏大厅界面按 ~ 键打开控制台"
    echo_info "💡 输入以上命令即可直连服务器"
    fi
}

# 其他选项函数
others() {
    while true; do
        echo "============================================"
        echo_info "其他选项"
        echo "1. 更新脚本"
        echo "2. 更新黑名单"
        echo "3. 删除所有MOD"
        echo "4. 删除DST服务器程序"
        echo "0. 返回主菜单"
        read -p "输入选项: " option

        case $option in
            1)
                echo_info "正在更新脚本..."
                if [ -f "x.sh" ]; then
                    mv "x.sh" "x.sh.bak"
                    echo_warning "已将原有的 x.sh 文件重命名为 x.sh.bak"
                fi
                if download "https://gitee.com/xiaochency/dstsh/raw/master/x.sh" 5 10; then
                    chmod 755 x.sh
                    echo_success "已成功更新脚本，请重新执行脚本"
                else
                    echo_error "更新脚本失败，请检查网络连接或URL是否正确"
                fi
                exit 0
                ;;
            2)
                echo_info "正在更新黑名单..."
                if [ -f "blocklist.txt" ]; then
                    mv "blocklist.txt" "blocklist.txt.bak"
                    echo_warning "已将原有的 blocklist.txt 文件重命名为 blocklist.txt.bak"
                fi
                if download "https://gitee.com/xiaochency/dstsh/raw/master/blocklist.txt" 5 10; then
                    cp -f blocklist.txt ~/.klei/DoNotStarveTogether/Cluster_1
                    cp -f blocklist.txt ~/.klei/DoNotStarveTogether/Cluster_2
                    echo_success "已成功更新黑名单"
                else
                    echo_error "更新黑名单失败，请检查网络连接或URL是否正确"
                fi
                ;;
            3)
                read -p "您确定要删除所有MOD吗？(y/n): " confirm
                if [[ $confirm == "y" || $confirm == "Y" ]]; then
                    echo_info "正在删除所有MOD..."
                    rm -rf ~/dst/ugc_mods/Cluster_1/Master/content/322330/*
                    rm -rf ~/dst/ugc_mods/Cluster_2/Master/content/322330/*
                    rm -rf ~/dst/ugc_mods/Cluster_1/Caves/content/322330/*
                    rm -rf ~/dst/ugc_mods/Cluster_2/Caves/content/322330/*
                    echo_success "已成功删除所有MOD"
                else
                    echo_warning "取消删除所有MOD"
                fi
                ;;
            4)
                read -p "您确定要删除DST服务器程序吗？(y/n): " confirm
                if [[ $confirm == "y" || $confirm == "Y" ]]; then
                    echo_info "正在删除DST服务器程序..."
                    rm -rf "$install_dir"
                    rm -rf "$steamcmd_dir"
                    echo_success "已成功删除DST服务器程序"
                else
                    echo_warning "取消删除DST服务器程序"
                fi
                ;;
            0)
                echo_info "返回主菜单"
                break
                ;;
            *)
                echo_error "无效选项，请重试"
                ;;
        esac
    done
}

# 主菜单
while true; do
    echo "-------------------------------------------------"
    echo -e "${GREEN}饥荒云服务器管理脚本1.3.4 By:xiaochency${NC}"
    echo "-------------------------------------------------"
    echo -e "${BLUE}请选择一个选项:${NC}"
    echo "-------------------------------------------------"
    echo -e "| ${CYAN}[1] 启动服务器${NC}          ${CYAN}[2] 更新服务器${NC}          |"
    echo "-------------------------------------------------"
    echo -e "| ${CYAN}[3] 查看服务器${NC}          ${CYAN}[4] 关闭服务器${NC}          |"
    echo "-------------------------------------------------"
    echo -e "| ${CYAN}[5] 更新模组配置${NC}        ${CYAN}[6] 监控服务器${NC}          |"
    echo "-------------------------------------------------"
    echo -e "| ${CYAN}[7] 存档管理${NC}            ${CYAN}[8] 服务器控制台${NC}        |"
    echo "-------------------------------------------------"
    echo -e "| ${CYAN}[9] 安装服务器${NC}          ${CYAN}[0] 更多${NC}                |"
    echo "-------------------------------------------------"

    read -p "输入您的选择 (0-9): " choice
    case $choice in
        1)
            while true; do
                echo "============================================"
                echo_info "请选择启动哪个服务器:"
                echo "1. 启动 Cluster_1Master"
                echo "2. 启动 Cluster_1Caves"
                echo "3. 启动 Cluster_1Master+Cluster_1Caves"
                echo "4. 启动 Cluster_2Master"
                echo "5. 启动 Cluster_2Caves"
                echo "6. 启动 Cluster_2Master+Cluster_2Caves"
                echo "0. 返回主菜单"

                read -p "输入您的选择 (0-6): " view_choice
                case $view_choice in
                    1)  start_server "Cluster_1" "Master" ;;
                    2)  start_server "Cluster_1" "Caves" ;;
                    3)  start_server "Cluster_1" "Master"; start_server "Cluster_1" "Caves" ;;
                    4)  start_server "Cluster_2" "Master" ;;
                    5)  start_server "Cluster_2" "Caves" ;;
                    6)  start_server "Cluster_2" "Master"; start_server "Cluster_2" "Caves" ;;
                    0)
                        break
                        ;;
                    *)
                        echo_error "无效选择. 请重试."
                        ;;
                esac
            done
            ;;
        2)
            Update_dst
            ;;
        3)  
            show_server_status
            echo "============================================"
            echo_info "当前运行的服务器如下："
            screen -ls
            while true; do
                echo_info "请选择一个选项:"
                echo "1. 查看 Cluster_1Master 服务器"
                echo "2. 查看 Cluster_1Caves 服务"
                echo "3. 查看 Cluster_2Master 服务器"
                echo "4. 查看 Cluster_2Caves 服务"
                echo "0. 返回主菜单"
                echo_warning "要退出 screen 会话, 请按 Ctrl+A+D."

                read -p "输入您的选择 (0-4): " view_choice
                case $view_choice in
                    1)
                        screen -r Cluster_1Master
                        ;;
                    2)
                        screen -r Cluster_1Caves
                        ;;
                    3)
                        screen -r Cluster_2Master
                        ;;
                    4)
                        screen -r Cluster_2Caves
                        ;;
                    0)
                        break
                        ;;
                    *)
                        echo_error "无效选择. 请重试."
                        ;;
                esac
            done
            ;;
        4)
            shutdown_server
            ;;
        5)
            UpdateMods
            ;;
        6)
            ms_servers
            ;;
        7)
            while true; do
                echo "============================================"
                echo_info "请选择一个选项:"
                echo "1. 备份存档"
                echo "2. 恢复存档"
                echo "3. 删除存档"
                echo "0. 返回主菜单"
                read -p "输入您的选择 (0-3): " view_choice

                case $view_choice in
                    1)
                        BackupSaves
                        ;;
                    2)
                        RestoreSaves
                        ;;
                    3)
                        DeleteSaves
                        ;;
                    0)
                        break
                        ;;    
                    *)
                        echo_error "无效选项，请重试"
                        ;;
                esac
            done
            ;;
        8)
            server_console
            ;;     
        9)
            Install_dst
            ;;
        0)
            others
            ;;
        *)
            echo_error "无效选择. 请重试."
            ;;
    esac
done

